package com.chen.controller.email;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chen.common.Constants;
import com.chen.common.Result;
import com.chen.entity.User;
import com.chen.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName InterfaceApiController.java
 * @Description TODO
 * @createTime 2023年04月19日 21:32:00
 */
@RestController
@RequestMapping("/api/service")
@Api(tags = "对接服务的API接口 获取QQ邮箱验证码")
public class InterfaceApiController {



    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService sysUserService;

    @Resource
    private JavaMailSender javaMailSender;

    /**
     * 邮箱号
     */
    @Value("${spring.mail.username}")
    private String email;


    @ApiOperation(value = "注册时发送邮件验证码")
    @GetMapping("/sendMailCode/{mail}")
    public Result sendMail(@PathVariable String mail) {
        if (!isEmail(mail)) {
//            return Result.fail().message("请输入正确格式的邮箱");
            return Result.error("2001","请输入正确格式的邮箱");
        }
        //redis邮箱存在则不在发送
        if (redisTemplate.hasKey(mail)) {
            return Result.success("发送成功");
        }
        User sysUserVo = new User();
        sysUserVo.setEmail(mail);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",mail);
        List<User> list = sysUserService.list(wrapper);
        //如果邮箱存在
        if (list.size()!=0) {
            return Result.error("2001","邮箱已被注册");
        }

        Random random = new Random();
        DecimalFormat sixdf = new DecimalFormat("000000");
        String code = sixdf.format(random.nextInt(1000000));

        try {
            // 存入到redis 邮箱、验证码、时间、单位
            redisTemplate.opsForValue().set(Constants.CAPTCHA_CODE_KEY + mail, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            // 发送邮件
            //mailServiceApi.sendQQMail(CollUtil.newArrayList(mail), "注册验证码", "您的验证码是：" + code + "，" + Constants.CAPTCHA_EXPIRATION + "分钟有效", false);


            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("注册验证码");
            message.setText("你的验证码是"+code+"有效期是"+Constants.CAPTCHA_EXPIRATION+"分钟"+","+"请不要告诉他人哦！");
            message.setFrom(email);
            message.setTo(mail);
            javaMailSender.send(message);

        } catch (Exception e) {
//            return Result.fail("失败").message("发送邮件失败");
            return Result.error("20001","发送邮件失败");
        }

        return Result.success("正在发送邮件，请注意查收");
    }

    @ApiOperation(value = "找回密码发送邮件验证码")
    @GetMapping("/sendRetrieveMail/{mail}")
    public Result sendRetrieveMail(@PathVariable String mail) {
//        mail = mail.trim();
        if (!isEmail(mail)) {
            return Result.error("2001","请输入正确格式的邮箱");
        }
//        //redis邮箱存在则不在发送
//        if (redisTemplate.hasKey("Retrieve-" + mail)) {
//            return Result.ok("发送成功");
//        }

        User sysUserVo = new User();
        sysUserVo.setEmail(mail);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",mail);
        List<User> list = sysUserService.list(wrapper);
        //如果邮箱不存在
        if (list.size()==0) {
            return Result.error("2001","账号不存在");
        }
        Random random = new Random();
        DecimalFormat sixdf = new DecimalFormat("000000");
        String code = sixdf.format(random.nextInt(1000000));

        //ALiMail aLiMail = new ALiMail(mail, "找回密码验证码", "您的验证码是：" + code + "，30分钟有效");

        // 存入到redis 邮箱、验证码、时间、单位
        try {
            //redisTemplate.opsForValue().set("Retrieve-" + mail, code, 10, TimeUnit.MINUTES);


            redisTemplate.opsForValue().set(Constants.CAPTCHA_CODE_KEY + mail, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

            //mailServiceApi.sendQQMail(CollUtil.newArrayList(mail), "找回密码验证码", "您的验证码是：" + code + "，30分钟有效", false);
            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("找回密码验证码");
            message.setText("您的验证码是"+code+"有效期是"+Constants.CAPTCHA_EXPIRATION+"分钟"+","+"请不要告诉他人哦！");
            message.setFrom(email);
            message.setTo(mail);
            javaMailSender.send(message);

        } catch (Exception e) {
            return Result.error("2001","发送邮件失败");
        }

        return Result.success("正在发送邮件，请注意查收");
    }


    public static boolean isEmail(String string) {
        if (string == null){
            return false;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        if (m.matches()) {
            return true;
        }else {
            return false;
        }
    }


}
